package com.gitee.chili.leisure.listener;

import cn.hutool.core.util.ReflectUtil;
import com.gitee.chili.leisure.game.Player;
import com.gitee.chili.leisure.game.PlayerFactory;
import com.gitee.chili.leisure.util.ClassUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Set;

@Slf4j
@Component
public class GameModeInstantRegisterListener implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(@NonNull ContextRefreshedEvent event) {
        log.info("register games mode instant");
        Set<Class<? extends Player>> classes = ClassUtil.getSubclasses(Player.class);

        log.debug("==============================================");
        classes.forEach(clazz -> {
            Method method = ReflectUtil.getMethod(clazz, "getType");
            try {
                Long mode = Long.parseLong(method.invoke(clazz.newInstance()).toString());
                log.debug("实例对应编号 ： {}  <=====> {}", clazz, mode);
                PlayerFactory.register(mode, clazz);
            } catch (IllegalAccessException | InvocationTargetException | InstantiationException e) {
                log.error("获取类指定游戏类型异常 :{}", e.getMessage(), e);
            }
        });
        log.debug("==============================================");

    }
}